package com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.core.utils.StringUtils;
import com.huaweicloud.sdk.hss.v5.HssClient;
import com.huaweicloud.sdk.hss.v5.model.ChangeEventRequest;
import com.huaweicloud.sdk.hss.v5.model.ChangeEventRequestInfo;
import com.huaweicloud.sdk.hss.v5.model.ChangeEventResponse;
import com.huaweicloud.sdk.hss.v5.model.EventDetailRequestInfo;
import com.huaweicloud.sdk.hss.v5.model.EventDetailResponseInfo;
import com.huaweicloud.sdk.hss.v5.model.EventManagementResponseInfo;
import com.huaweicloud.sdk.hss.v5.model.ListSecurityEventsRequest;
import com.huaweicloud.sdk.hss.v5.model.ListSecurityEventsResponse;
import com.huaweicloud.sdk.hss.v5.model.OperateEventRequestInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ChangeEventDemo {
    private static final Logger logger = LoggerFactory.getLogger(ChangeEventDemo.class.getName());

    /**
     * args[0] = "<YOUR IAM_END_POINT>"
     * args[1] = "<YOUR END_POINT>"
     * args[2] = "<YOUR AK>"
     * args[3] = "<YOUR SK>"
     * args[4] = "<Event Category, 事件分类主要有两种，包括host（主机）和container（容器）>"
     * args[5] = "<YOUR REGION_ID>"
     * args[6] = "<OPERATE TYPE, 操作类型包括mark_as_handled(手动处理), ignore(忽略), unhandle(取消手动处理)等>"
     * args[7] = "<REMARK, remark(备注), 非必填>"
     *
     * @param args
     */

    public static void main(String[] args) {
        if (args.length != 8) {
            logger.info("Illegal Arguments");
        }

        String iamEndpoint = args[0];
        String endpoint = args[1];

        String ak = args[2];
        String sk = args[3];

        // 第一步：输入事件分类、操作类型
        // 事件分类主要有两种，包括host（主机）和container（容器）
        String category = args[4];
        String regionId = args[5];

        // 操作类型包括mark_as_handled(手动处理), ignore(忽略), unhandle(取消手动处理)等
        String operateType = args[6];
        // remark(备注), 非必填
        String remark = args[7];

        ICredential auth = new BasicCredentials().withIamEndpoint(iamEndpoint).withAk(ak).withSk(sk);

        // 根据需要配置是否跳过SSL证书验证
        HttpConfig httpConfig = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true);
        HssClient client = HssClient.newBuilder()
            .withCredential(auth)
            .withRegion(new Region(regionId, endpoint))
            .withHttpConfig(httpConfig)
            .build();
        String handleStatus = "unhandled";
        // 第二步：查入侵事件列表
        List<EventManagementResponseInfo> eventManagementList = getEventManagementList(client, regionId, category,
            handleStatus);
        // 第三步：获取告警信息
        EventManagementResponseInfo securityEvent = getEventManagement(eventManagementList);
        if (securityEvent == null) {
            logger.info("securityEvent is empty");
            return;
        }
        // 封装请求体
        ChangeEventRequest request = new ChangeEventRequest();
        request.setRegion(regionId);
        ChangeEventRequestInfo body = new ChangeEventRequestInfo();
        body.setOperateType(operateType);
        if (!StringUtils.isEmpty(remark)) {
            body.setHandler(remark);
        }
        List<OperateEventRequestInfo> operateEventList = new ArrayList<>();
        OperateEventRequestInfo eventInfo = new OperateEventRequestInfo();
        eventInfo.setEventId(securityEvent.getEventId());
        eventInfo.setEventClassId(securityEvent.getEventClassId());
        eventInfo.setEventType(securityEvent.getEventType());
        eventInfo.setOccurTime(securityEvent.getOccurTime());
        eventInfo.setOperateDetailList(transEventDetailFunction.apply(securityEvent.getOperateDetailList()));
        operateEventList.add(eventInfo);
        body.setOperateEventList(operateEventList);
        request.setBody(body);
        // 第四步：处理告警事件
        changeEvent(client, request);
    }

    /**
     * 转换请求对象
     */
    private static Function<List<EventDetailResponseInfo>, List<EventDetailRequestInfo>> transEventDetailFunction
        = listEventDetailResponse -> {
        if (listEventDetailResponse == null || listEventDetailResponse.isEmpty()) {
            logger.info("listEventDetailResponse is empty");
            return new ArrayList<>();
        }
        return listEventDetailResponse.stream().map(eventDetailResponseInfo -> {
            EventDetailRequestInfo detail = new EventDetailRequestInfo();
            detail.setAgentId(eventDetailResponseInfo.getAgentId());
            detail.setHash(eventDetailResponseInfo.getHash());
            detail.setKeyword(eventDetailResponseInfo.getKeyword());
            return detail;
        }).collect(Collectors.toList());
    };

    /**
     * 查入侵事件列表
     *
     * @param client
     * @param
     * @return
     */
    private static List<EventManagementResponseInfo> getEventManagementList(HssClient client, String region,
        String category, String handleStatus) {
        ListSecurityEventsRequest request = new ListSecurityEventsRequest();
        request.setRegion(region);
        request.setCategory(category);
        request.setHandleStatus(handleStatus);
        ListSecurityEventsResponse listSecurityEventsResponse = client.listSecurityEvents(request);
        if (listSecurityEventsResponse != null && listSecurityEventsResponse.getDataList() != null
            && !listSecurityEventsResponse.getDataList().isEmpty()) {
            return listSecurityEventsResponse.getDataList();
        }
        return null;
    }

    /**
     * 获取告警信息
     *
     * @param dataList
     * @return
     */
    private static EventManagementResponseInfo getEventManagement(List<EventManagementResponseInfo> dataList) {
        if (dataList != null && dataList.size() > 0) {
            return dataList.get(0);
        }
        return null;
    }

    /**
     * 处理告警事件
     *
     * @param client
     * @param request
     */
    private static void changeEvent(HssClient client, ChangeEventRequest request) {
        try {
            if (request == null) {
                logger.info("ChangeEventRequest is empty");
                return;
            }
            ChangeEventResponse response = client.changeEvent(request);
            logger.info(response.toString());
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(),
                e.getErrorMsg());
        }
    }
}
